const app = getApp()

Page({
  data: {
    photo: {},
    staticUrl: app.globalData.staticUrl,

  },

  onLoad(options) {
    if (options.info) {
      const info = JSON.parse(decodeURIComponent(options.info));
      this.setData({ photo: info });
    }

    if (app.checkislogin()) {
      this.getPhotos(this.data.photo.id);
    } else {
      wx.showModal({
        title: '请先登录',
        content: '需要登录后才能投票',
        confirmText: '去登录',
        cancelText: '取消',
        success(res) {
          if (res.confirm) {
            wx.navigateTo({
              url: '/pages/login/login'
            });
          }
        }
      });
    }

  },

  // 模拟获取照片详情
  getPhotoDetail(id) {
    // 这里替换成你的接口
    const mock = {
      id: id,
      name: '张三',
      url: 'https://picsum.photos/500/700?random=1',
      votes: 100
    };
    this.setData({ photo: mock });
  },

 // 投票
 vote(e) {
  const user_id = getApp().globalData.userInfo.userID;
   const id = e.currentTarget.dataset.id;
   let that = this;
  wx.showLoading({ title: '投票中...' });
  wx.request({
    url: 'https://mapp.scoringchina.com/interface/xijiuopen/vote/dovote',
    method: 'POST',
    header: {
      'content-type': 'application/x-www-form-urlencoded'  
    },
    data: {
      user_id,
      vote_user_id:id
    },
    success: (res) => {
      console.log('--------投票成功0---', res.data.errorcode);
        let message = res.data.errorcode.message;
          if (message.indexOf('succ') > -1) {
            wx.showToast({ title: '投票成功', icon: 'none', duration: 1000});
          } else {
            wx.showToast({ title: res.data.errorcode.message, icon: 'none',duration: 1000});
          }
          setTimeout(() => {
              this.getPhotos(that.data.photo.id);
          }, 1000);
    },
    complete: () => {
    }
  });
  },
 // 获取详情
getPhotos(id) {
  wx.showLoading({ title: '加载中...' });
  wx.request({
    url: 'https://mapp.scoringchina.com/interface/xijiuopen/vote/votedetail',
    method: 'GET',
    data: {
      id,
    },
    success: (res) => {
      if (res.data ) {
        console.log(res.data);
        this.setData({ photo: res.data.data });
      } else {
        wx.showToast({ title: '数据格式异常', icon: 'none' });
      }
    },
    fail: () => {
      wx.showToast({ title: '加载失败', icon: 'none' });
    },
    complete: () => {
      wx.hideLoading();
    }
  });
},

  // 分享
  onShareAppMessage() {
    return {
      title: `${this.data.photo.username} 邀请你帮忙投票`,
      path: `/pages/vote/detail?info=${encodeURIComponent(JSON.stringify(this.data.photo))}`,
      imageUrl: this.data.photo.image
    };
  }
});
